package cn.huobi.org.service.impl;

import cn.huobi.basic.config.BussinessException;
import cn.huobi.basic.query.BaseQuery;
import cn.huobi.basic.util.*;
import cn.huobi.org.domain.Employee;
import cn.huobi.org.domain.Shop;
import cn.huobi.org.domain.ShopAuditLog;
import cn.huobi.org.eum.ShopStateEum;
import cn.huobi.org.mapper.EmployeeMapper;
import cn.huobi.org.mapper.ShopAuditLogMapper;
import cn.huobi.org.mapper.ShopMapper;
import cn.huobi.org.service.EmployeeService;
import cn.huobi.org.service.ShopService;
import cn.huobi.basic.service.impl.BaseServiceImpl;
import cn.huobi.org.vo.ShopEchartsVo;
import cn.huobi.user.domain.Logininfo;
import cn.huobi.user.domain.User;
import cn.huobi.user.dto.PhoneRegisterDto;
import cn.huobi.user.mapper.LogininfoMapper;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huobi
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;


    /**
     * 店铺入驻
     */
    @Override
    public void settlement(Shop shop) {

        Employee admin = shop.getAdmin();
        Employee employee = this.verify(shop, admin);
        /**
         * 将信息存入数据库
         */
        // 添加店铺
        shopMapper.add(shop);
        // 添加店铺管理员
        if (employee == null){
            employee = admin;
            employeeService.add(employee);
        }
        Logininfo logininfo = this.empConvertLogininfo(employee);
        logininfoMapper.add(logininfo);
        employee.setLogininfoId(logininfo.getId());
        // 修改管理员的shopId
        //System.out.println(shop.getId());
        employee.setShopId(shop.getId());
        employeeService.update(employee);
        // 修改店铺的adminId
        Shop uptShop = new Shop();
        uptShop.setId(shop.getId());
        uptShop.setAdminId(employee.getId());
        //System.out.println(employee.getId());
        shopMapper.update(uptShop);
    }

    /**
     * 将emp转为logininfo
     */
    private Logininfo empConvertLogininfo (Employee employee){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + employee.getPassword();
        // MD5加密
        String encryp = MD5Utils.encrypByMd5(password);
        return Logininfo.builder()
                .username(employee.getUsername())
                .phone(employee.getPhone())
                .email(employee.getEmail())
                .salt(salt)
                .password(encryp)
                .type(1)
                .disable(true)
                .build();
    }

    /**
     * 店铺审核通过
     */
    @Override
    public void auditPass(ShopAuditLog shopAuditLog) {
        //判断备注是否为空
        if (StringUtils.isBlank(shopAuditLog.getNote())){
            throw new BussinessException("备注不能为空！");
        }
        /*
         * 修改店铺状态为 审核通过
         */
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        /*
         * 添加店铺日志
         */
        shopAuditLog.setAuditId(1025L);
        shopAuditLogMapper.add(shopAuditLog);
        /*
         * 发送邮件通知用户
         */
//        // 1.创建复杂邮件对象
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        // 2.发送复杂邮件的工具类
//        MimeMessageHelper helper = null;
//        try {
//            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("1605503320@qq.com");
//            helper.setSubject("宠物之家店铺入驻审核结果");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>恭喜您店铺审核通过，点击下方链接激活店铺</h1>"+
//                    "http://localhost:8080/shop/active/"+shopAuditLog.getShopId(),true);
//            // 5.设置收件人
//            helper.setTo("1605503320@qq.com");
//        } catch (MessagingException e) {
//            e.printStackTrace();
//            throw new BussinessException("发送邮件失败！");
//        }
//        // 6.发送邮件
//        javaMailSender.send(mimeMessage);
        String text = "<h1>恭喜您店铺审核通过，点击下方链接激活店铺</h1>"+
                "http://localhost:8081/#/shopActive?shopId="+shopAuditLog.getShopId();
        EmailUtil.sendEmail("宠物之家店铺入驻审核结果",text,"1605503320@qq.com");
    }

    /**
     * 店铺激活
     */
    @Override
    public void active(Long id) {
        // 修改店铺状态
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    /**
     * Echarts报表
     * @return
     */
    @Override
    public Map<String, Object> echarts() {
        Map<String, Object> result = new HashMap<>();
        List<ShopEchartsVo> vo = shopMapper.echarts();
        List<Integer> x = vo.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());
        // 等同于
//        List<Integer> xT = new ArrayList<>();
//        for (ShopEchartsVo echartsVo : vo) {
//            xT.add(echartsVo.getState());
//        }
        List<Integer> y = vo.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());
        ArrayList<Object> realX = new ArrayList<>();
        for (Integer xTemp : x) {
            String stateName = ShopStateEum.getNameByCode(xTemp);
            realX.add(stateName);
        }
        result.put("x",realX);
        result.put("y",y);
        return result;
    }

    /**
     * 店铺驳回
     */
    @Override
    public void auditReject(ShopAuditLog shopAuditLog) {
        // 判断备注是否为空
        if (StringUtils.isBlank(shopAuditLog.getNote())){
            throw new BussinessException("备注不能为空！");
        }
        /*
         * 修改店铺状态
         */
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        /*
         * 添加店铺日志
         */
        shopAuditLog.setAuditId(1025L);
        shopAuditLogMapper.add(shopAuditLog);
        /*
         * 发送邮件通知用户
         */
//        // 1.创建复杂邮件对象
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        // 2.发送复杂邮件的工具类
//        MimeMessageHelper helper = null;
//        try {
//            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("1605503320@qq.com");
//            helper.setSubject("宠物之家店铺入驻审核结果");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>您店铺审核驳回，点击下方链接重新填写店铺信息</h1>"+
//                    "http://localhost:8081/#/registerAgain?shopId="+shopAuditLog.getShopId(),true);
//            // 5.设置收件人
//            helper.setTo("1605503320@qq.com");
//        } catch (MessagingException e) {
//            e.printStackTrace();
//            throw new BussinessException("发送邮件失败！");
//        }
//        // 6.发送邮件
//        javaMailSender.send(mimeMessage);
        String text = "<h1>您的店铺入驻申请被驳回，请点击下方链接重新填写店铺信息,"+shopAuditLog.getNote()+"</h1>"+
                "http://localhost:8081/#/registerAgain?shopId="+shopAuditLog.getShopId();
        EmailUtil.sendEmail("宠物之家店铺入驻审核结果",text,"1605503320@qq.com");

    }

    /**
     * 批量添加
     * @param shops
     */
    @Override
    public void addAll(List<Shop> shops) {
        shopMapper.addAll(shops);
    }


    /**
     * 参数校验
     */
    private Employee verify(Shop shop, Employee admin) {
        // 判断店铺名称是否为空
        if (StringUtils.isBlank(shop.getName())){
            // 抛异常
            throw new BussinessException("店铺名称不能为空!");
        }
        // 判断座机是否为空
        if (StringUtils.isBlank(shop.getTel())){
            throw new BussinessException("座机不能为空!");
        }
        // 判断店铺地址是否为空
        if (StringUtils.isBlank(shop.getAddress())){
            throw new BussinessException("店铺地址不能为空!");
        }
        /**
         * logo AI验证
         */
        // 判断店铺名称是否合规
        if (!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new BussinessException("店铺名称不合规！");
        }
        // 判断店铺logo是否合规
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())){
            throw new BussinessException("店铺logo不合规！");
        }
        // 判断账号是否为空
        if (StringUtils.isBlank(admin.getUsername())){
            throw new BussinessException("账号不能为空!");
        }
        // 判断手机号是否为空
        if (StringUtils.isBlank(admin.getPhone())){
            throw new BussinessException("手机号不能为空!");
        }
        // 判断电子邮箱是否为空
        if (StringUtils.isBlank(admin.getEmail())){
            throw new BussinessException("电子邮箱不能为空!");
        }
        // 判断两次密码是否相同
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BussinessException("两次密码不相同!");
        }
        // 通过店铺名判断店铺是否存在
        Shop tmpShop = shopMapper.findByName(shop.getName());
        if (tmpShop != null){
            throw new BussinessException("店铺已存在");
        }
        // 判断当前店铺管理员是否已经管理其他店铺
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (employee != null && employee.getShopId() != null){
            Shop shopById = shopMapper.findById(employee.getShopId());
            if (shopById.getAdminId().equals(employee.getId())){
                throw new BussinessException("当前店铺管理员已管理店铺，不可管理多个店铺！");
            }
        }
        return employee;
    }

    /**
     * 店铺日志查询
     */
    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        PageList<Shop> shopPageList = super.queryByPage(query);
        // 非空判断
        // 获取查询到的店铺集合
        List<Shop> rows = shopPageList.getRows();
        // 取出店铺id
        List<Long> shopIds = rows.stream().map(Shop::getId).collect(Collectors.toList());
        // 根据店铺id查询日志
        List<ShopAuditLog> auditLogs = shopAuditLogMapper.findByShopIds(shopIds);
        // 将日志集合根据店铺id分组
        Map<Long, List<ShopAuditLog>> logMap = auditLogs.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));
        // 等同于
//        Map<Long, List<ShopAuditLog>> logMap = new HashMap<>();
//        for (ShopAuditLog auditLog : auditLogs) {
//            List<ShopAuditLog> tmpList = logMap.get(auditLog.getShopId());
//            if (CollectionUtils.isEmpty(tmpList)){
//                tmpList = new ArrayList<>();
//            }
//            tmpList.add(auditLog);
//            logMap.put(auditLog.getShopId(),tmpList);
//        }
        // 遍历
        rows.forEach(row->{
            row.setAuditLogs(logMap.get(row.getId()));
        });
        return shopPageList;
    }
}
